import { Request, Response } from 'express';
import { ArticleService } from '../services/articleService';
import * as ExcelJS from 'exceljs';

const articleService = new ArticleService();

export class ArticleController {
  // 获取文章列表
  async getArticles(req: Request, res: Response) {
    try {
      const {
        page = 1,
        limit = 10,
        categoryId,
        status,
        keyword,
        userId,
        isTop,
        isRecommend,
      } = req.query;

      const result = await articleService.getArticles({
        page: Number(page),
        limit: Number(limit),
        categoryId: categoryId ? Number(categoryId) : undefined,
        status: status !== undefined ? String(status) === 'true' : undefined,
        keyword: keyword as string,
        userId: userId ? Number(userId) : undefined,
        isTop: isTop !== undefined ? isTop === 'true' : undefined,
        isRecommend: isRecommend !== undefined ? isRecommend === 'true' : undefined,
        sort: req.query.sort as string,
      });

      if (!result.success) {
        return res.status(400).json(result);
      }

      res.json(result);
    } catch (error) {
      console.error('获取文章列表失败:', error);
      res.status(500).json({
        success: false,
        message: '获取文章列表失败',
        error: error instanceof Error ? error.message : '未知错误',
      });
    }
  }

  // 根据ID获取文章详情
  async getArticleById(req: Request, res: Response) {
    try {
      const { id } = req.params;
      const result = await articleService.getArticleById(Number(id));

      if (!result.success) {
        return res.status(404).json(result);
      }

      res.json(result);
    } catch (error) {
      console.error('获取文章详情失败:', error);
      res.status(500).json({
        success: false,
        message: '获取文章详情失败',
        error: error instanceof Error ? error.message : '未知错误',
      });
    }
  }

  // 根据slug获取文章详情
  async getArticleBySlug(req: Request, res: Response) {
    try {
      const { slug } = req.params;
      const result = await articleService.getArticleBySlug(slug);

      if (!result.success) {
        return res.status(404).json(result);
      }

      res.json(result);
    } catch (error) {
      console.error('获取文章详情失败:', error);
      res.status(500).json({
        success: false,
        message: '获取文章详情失败',
        error: error instanceof Error ? error.message : '未知错误',
      });
    }
  }

  // 创建文章
  async createArticle(req: Request, res: Response) {
    try {
      const userId = req.user?.id;
      if (!userId) {
        return res.status(401).json({
          success: false,
          message: '未授权'
        });
      }

      const result = await articleService.createArticle(req.body, userId);

      if (!result.success) {
        return res.status(400).json(result);
      }

      res.status(201).json({
        ...result,
        message: '文章创建成功',
      });
    } catch (error) {
      console.error('创建文章失败:', error);
      res.status(500).json({
        success: false,
        message: '创建文章失败',
        error: error instanceof Error ? error.message : '未知错误',
      });
    }
  }

  // 更新文章
  async updateArticle(req: Request, res: Response) {
    try {
      const { id } = req.params;
      const result = await articleService.updateArticle(Number(id), req.body);

      if (!result.success) {
        return res.status(400).json(result);
      }

      res.json({
        ...result,
        message: '文章更新成功',
      });
    } catch (error) {
      console.error('更新文章失败:', error);
      res.status(500).json({
        success: false,
        message: '更新文章失败',
        error: error instanceof Error ? error.message : '未知错误',
      });
    }
  }

  // 删除文章
  async deleteArticle(req: Request, res: Response) {
    try {
      const { id } = req.params;
      const deleteBy = (req as any).user?.id; // 获取当前操作用户ID
      const result = await articleService.deleteArticle(Number(id), deleteBy);

      if (!result.success) {
        return res.status(400).json(result);
      }

      res.json({
        ...result,
        message: '文章删除成功',
      });
    } catch (error) {
      console.error('删除文章失败:', error);
      res.status(500).json({
        success: false,
        message: '删除文章失败',
        error: error instanceof Error ? error.message : '未知错误',
      });
    }
  }

  // 获取文章统计
  async getArticleStats(req: Request, res: Response) {
    try {
      const result = await articleService.getArticleStats();

      if (!result.success) {
        return res.status(400).json(result);
      }

      res.json(result);
    } catch (error) {
      console.error('获取文章统计失败:', error);
      res.status(500).json({
        success: false,
        message: '获取文章统计失败',
        error: error instanceof Error ? error.message : '未知错误',
      });
    }
  }

  // 获取推荐文章
  async getRecommendArticles(req: Request, res: Response) {
    try {
      const { limit = 5 } = req.query;
      const result = await articleService.getRecommendArticles(Number(limit));

      if (!result.success) {
        return res.status(400).json(result);
      }

      res.json(result);
    } catch (error) {
      console.error('获取推荐文章失败:', error);
      res.status(500).json({
        success: false,
        message: '获取推荐文章失败',
        error: error instanceof Error ? error.message : '未知错误',
      });
    }
  }

  // 获取置顶文章
  async getTopArticles(req: Request, res: Response) {
    try {
      const { limit = 3 } = req.query;
      const result = await articleService.getTopArticles(Number(limit));

      if (!result.success) {
        return res.status(400).json(result);
      }

      res.json(result);
    } catch (error) {
      console.error('获取置顶文章失败:', error);
      res.status(500).json({
        success: false,
        message: '获取置顶文章失败',
        error: error instanceof Error ? error.message : '未知错误',
      });
    }
  }

  // 导出文章列表
  async exportArticles(req: Request, res: Response) {
    try {
      const {
        categoryId,
        status,
        keyword,
        userId,
        isTop,
        isRecommend,
        sort,
      } = req.query;

      // 获取所有符合条件的数据（不分页）
      const result = await articleService.getArticles({
        page: 1,
        limit: 10000, // 设置一个很大的数字来获取所有数据
        categoryId: categoryId ? Number(categoryId) : undefined,
        status: status !== undefined ? String(status) === 'true' : undefined,
        keyword: keyword as string,
        userId: userId ? Number(userId) : undefined,
        isTop: isTop !== undefined ? isTop === 'true' : undefined,
        isRecommend: isRecommend !== undefined ? isRecommend === 'true' : undefined,
        sort: sort as string,
      });

      if (!result.success) {
        return res.status(400).json(result);
      }

      const articles = result.data.articles;

      // 创建Excel工作簿
      const workbook = new ExcelJS.Workbook();
      const worksheet = workbook.addWorksheet('文章列表');

      // 设置列标题
      worksheet.columns = [
        { header: '标题', key: 'title', width: 30 },
        { header: '作者', key: 'author', width: 15 },
        { header: '创作者', key: 'creator', width: 15 },
        { header: '发布者', key: 'publisher', width: 15 },
        { header: '阅读数量', key: 'views', width: 12 },
        { header: '发布时间', key: 'publishedAt', width: 20 },
        { header: '创建时间', key: 'createdAt', width: 20 },
        { header: '状态', key: 'status', width: 10 },
        { header: '分类', key: 'category', width: 15 },
        { header: '置顶', key: 'isTop', width: 8 },
        { header: '推荐', key: 'isRecommend', width: 8 },
      ];

      // 添加数据行
      articles.forEach((article: any) => {
        worksheet.addRow({
          title: article.title,
          author: article.author,
          creator: article.user?.username || '未知',
          publisher: article.user?.username || '未知',
          views: article.views,
          publishedAt: article.publishedAt ? new Date(article.publishedAt).toLocaleString('zh-CN') : '未发布',
          createdAt: new Date(article.createdAt).toLocaleString('zh-CN'),
          status: article.status ? '已发布' : '草稿',
          category: article.category?.name || '未分类',
          isTop: article.isTop ? '是' : '否',
          isRecommend: article.isRecommend ? '是' : '否',
        });
      });

      // 设置表头样式
      worksheet.getRow(1).font = { bold: true };
      worksheet.getRow(1).fill = {
        type: 'pattern',
        pattern: 'solid',
        fgColor: { argb: 'FFE6E6FA' },
      };

      // 生成文件名
      const now = new Date();
      const dateStr = now.toISOString().split('T')[0];
      const fileName = `文章列表_${dateStr}.xlsx`;

      // 设置响应头
      res.setHeader('Content-Type', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
      res.setHeader('Content-Disposition', `attachment; filename="${encodeURIComponent(fileName)}"`);

      // 写入响应流
      await workbook.xlsx.write(res);
      res.end();
    } catch (error) {
      console.error('导出文章失败:', error);
      res.status(500).json({
        success: false,
        message: '导出文章失败',
        error: error instanceof Error ? error.message : '未知错误',
      });
    }
  }
} 